const Base = require('./base.js');
const moment = require('moment');
const xxphoto = 'https://www.coastalinfo.cn/coastalShop/static/temp/xxhg.jpg';
const probability = 10;//中奖概率，0-100之间，越接近0说明概率越小
//抽奖管理
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {//获取执行中的抽奖
        const page = this.get('page') || 1;
        const size = this.get('size') || 6;
        const sortField = this.get('sortfield') || 'id asc';
        const goodsname = this.get('name') || '';
        const state = this.get('state') || 1;
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        let seachdata = { id: ['>', 0] }, timesearch = {};
        if (goodsname) {
            seachdata['name'] = ['like', `%${goodsname}%`];
        }
        if (state || state === 0) {//是否停止
            seachdata['status'] = state;
        }
        if (begin) {
            seachdata['begin_time'] = ['egt', begin];
        }
        if (end) {
            seachdata['end_time'] = ['elt', end];
        }

        const model = this.model('lottery');
        const data = await model.where(seachdata)
            .order([sortField]).page(page, size).countSelect();
        for (const item of data.data) {
            item.statusText = this.getStatusText(item.status);
            item.usersum = await this.model('lottery_user').where({ lottery_id: item.id }).count('distinct user_id');
            item.usernumber = await this.model('lottery_user').where({ lottery_id: item.id }).count('id');
            item.userprizesum = await this.model('lottery_user').where({ lottery_id: item.id, lottery_row_id: ['>', 0] }).count('distinct user_id');
            item.userprizenumber = await this.model('lottery_user').where({ lottery_id: item.id, lottery_row_id: ['>', 0] }).count('id');
        }
        return this.success(data);
    }

    /**
     * 进入抽奖页
     */
    async detailAction() {
        const model = this.model('lottery');
        const id = this.get('id') || 0;
        if (id < 1) {
            return this.fail(400, '缺少参数抽奖id');
        }
        const data = await model.where({ id: id }).find();
        data.prize = await this.model('lottery_table').where({ 'lottery_id': id }).order('number ASC').select();
        data.myintersum = await this.model('lottery_user').where({ lottery_id: id, user_id: think.userId }).count('id');
        data.myprizesum = await this.model('lottery_user').where({ lottery_id: id, user_id: think.userId, lottery_row_id: ['>', 0] }).count('id');
        return this.success(data);
    }
    /**
    * 我的中奖明细
    */
    async prizeDetailAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const id = this.get('id') || 0;
        const sortField = this.get('sortfield') || 'hiolabs_lottery_user.add_time DESC';
        const goodsname = this.get('goodsname') || '';
        const goods_id = this.get('goods_id') || 0;
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        const status = this.get('status') || '';
        const iswin = this.get('iswin') || 0;
        let name = this.get('name') || '';
        const buffer = Buffer.from(name);
        let nickname = buffer.toString('base64');

        let searchData = { 'hiolabs_lottery_user.user_id': think.userId }, timesearch = {};
        if (id) {
            searchData['hiolabs_lottery_user.lottery_id'] = id;
        }
        if (iswin) {
            searchData['hiolabs_lottery_user.lottery_row_id'] = ['>', 0];
        }
        if (goods_id) {
            searchData['lr.goods_id'] = goods_id;
        }
        if (goodsname) {
            searchData['lr.original_name'] = ['like', `%${goodsname}%`];
        }
        if (status || status === 0) {
            searchData['hiolabs_lottery_user.status'] = status;
        }

        // if(name){
        //     searchData['_complex'] = {
        //         'ou.nickname':['like', `%${nickname}%`],
        //         'ou.name':['like', `%${name}%`],
        //         'ou.mobile':['like', `%${name}%`],
        //         _logic:'or'
        //     };
        // }

        if (begin || end) {
            if (begin) {
                timesearch['egt'] = parseInt(new Date(begin).getTime() / 1000);
            }
            if (end) {
                timesearch['elt'] = parseInt(new Date(end).getTime() / 1000);
            }
            searchData['hiolabs_lottery_user.add_time'] = timesearch;
        }

        const model = this.model('lottery_user');
        const data = await model.join({ table: 'lottery_row', join: 'left', as: 'lr', on: ['lottery_row_id', 'id'] })
            // .join({ table: 'user',  join: 'left', as:'ou', on: ['hiolabs_lottery_user.user_id', 'id'] })
            .where(searchData)
            .field('hiolabs_lottery_user.*,lr.name,lr.original_name,lr.type,lr.pic')
            .order(sortField).page(page, size).countSelect();
        for (const item of data.data) {
            // item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.nowstatus = await this.getnowStatusText(item.status);//现状态
            item.add_time = moment.unix(item.add_time).format('YYYY-MM-DD HH:mm:ss');
            if (!item.name) {
                item.name = '未中奖';
                item.nowstatus = '--';
            }
            item.type=item.type?item.type:0;
        }

        return this.success(data);
    }

    async readAction() {
        const model = this.model('lottery');
        const id = this.get('id');
        const data = await model.where({ id: id }).find();
        data.prize = await this.model('lottery_row').where({ 'lottery_id': id }).select();
        return this.success(data);
    }


    /**
     * 开始抽奖(中奖逻辑)
     */
    async startLotteryAction() {
        const model = this.model('lottery');
        const rmodel = this.model('lottery_row');
        const tmodel = this.model('lottery_table');
        const id = this.post('id') || 0;
        if (id < 1) {
            return this.fail(400, '缺少参数抽奖id');
        }
        const lottery = await model.where({ id: id }).find();
        switch (lottery.status) {
            case 0:
                return this.fail(400, '活动未开始！');
            case 2:
                return this.fail(400, '活动已终止！');
            case 3:
                return this.fail(400, '活动已经结束了！');
            default:

        }
        const prizesum = await this.model('lottery_row').where({ lottery_id: id }).sum('amount');
        const sendnum = await this.model('lottery_row').where({ lottery_id: id }).sum('send');
        if (prizesum - sendnum <= 0) {
            return this.fail(400, '来晚了，奖品已被抽光');
        }
        const internum = await this.model('lottery_user').where({ lottery_id: id, user_id: think.userId }).count('id');
        if (lottery.times && lottery.times <= internum) {
            return this.fail(400, '每人限抽奖' + lottery.times + '次，你已达到上限');
        }
        const userinfo = await this.model('user').where({id:think.userId}).find();
        if(lottery.cost>userinfo.integral){
            return this.fail(400, '积分不够了');
        }

        let shu = Math.floor(Math.random() * 1000);
        let data = { lottery_row_id: 0,type:0, msg: '没有抽中呢，继续加油',id:0};
        const prizeData = await rmodel.where('lottery_id =' + id + ' and amount-send>0').select();
        const prizecount= await rmodel.where('lottery_id =' + id).count('id');
        if(parseInt(prizecount)>7) probability=0;//如果8个都是奖品，中奖概率应该是0%
        if(shu<=(1000-1000 * probability / 100)){
            const numbers = await tmodel.where({lottery_id: id,lottery_row_id: 0}).getField('number');
            if(think.isEmpty(numbers)) return this.fail(400, '来晚了，奖品已被抽光');
            data.number=numbers[Math.floor(Math.random() * numbers.length)];
            await this.model('lottery_user').add({
                lottery_id: id,
                user_id: think.userId,
                lottery_row_id: 0,
                add_time: Math.floor(new Date().getTime()/1000)
            });
        }else{
            if(think.isEmpty(prizeData)) return this.fail(400, '来晚了，奖品已被抽光');
            let inner = Math.floor(Math.random() * prizeData.length);
            data.lottery_row_id=prizeData[inner].id;
            data.type=prizeData[inner].type;
            data.msg='恭喜，你抽中了'+prizeData[inner].name;
            data.msg=data.type===1?data.msg+',将在三个工作日发放至你的账户，请注意查收':
                    data.msg+',请填写资料后领取';
            const numdta = await tmodel.where({lottery_id: id,lottery_row_id: prizeData[inner].id}).find();
            data.number= numdta.number;
            //修改send值，并添加中奖记录
            await rmodel.where({id:prizeData[inner].id}).increment('send', 1);
            data.id = await this.model('lottery_user').add({
                lottery_id: id,
                user_id: think.userId,
                lottery_row_id: prizeData[inner].id,
                add_time: Math.floor(new Date().getTime()/1000)
            });
        }
        //扣积分
        await this.model('user').where({id: think.userId}).decrement('integral',lottery.cost);
        //加记录
        await this.model('task_integral').add({
            user_id: think.userId,
            integral:lottery.cost*-1,
            reason:'抽奖',
            is_finish:1
        });

        return this.success(data);

    }

    //填写资料并领取奖品
    async takeInfoAction() {
        const model = this.model('lottery_user');
        const id = this.post('id');
        const values = this.post();
        if(!values['receive_name']||!values['receive_mobile']||!values['receive_addr']){
            this.fail(400,'请填写完整信息');
        }
        const rdata = await model.join({ table: 'lottery_row', join: 'left', as: 'lr', on: ['lottery_row_id', 'id'] })
            .where({ 'hiolabs_lottery_user.id': id,type:2 }).find();
        let data;
        if(!think.isEmpty(rdata)){
            values['info_time']=Math.floor(new Date().getTime()/1000);
            values['status']=1;
            data = await model.where({ id: id }).update(values);
        }else{
            data=0;
        }
        return this.success(data);
    }


    getStatusText(status) {
        switch (status) {
            case 0:
                return '未开始';
            case 1:
                return '执行中';
            case 2:
                return '中止';
            case 3:
                return '结束';
            default:
                return '未开始';
        }
    }
    getnowStatusText(status) {
        switch (status) {
            case 0:
                return '未领取';
            case 1:
                return '待发放';
            case 2:
                return '已领取';
            default:
                return '未领取';
        }
    }


};